<template>
    <div class="rules-form-modal-wrapper">
        <el-dialog :model-value="props.value" :title="dialog.title" :width="dialog.width" destroy-on-close>
            <el-form ref="ruleFormRef" :model="formData" :rules="ruleForm" label-width="110px" :disabled="isLook()">
                <el-form-item label="规则名称" prop="displayName">
                    <el-input
                        v-model="formData.displayName"
                        @input="value => (formData.displayName = value.trim())"
                        placeholder="请输入规则名称"
                        maxlength="50"
                    />
                </el-form-item>
                <el-form-item label="模型名称">
                    <el-input :value="detailData.displayName" disabled />
                </el-form-item>
                <el-form-item label="标识符">
                    <el-input disabled :value="row?.ruleName" placeholder="系统自动生" />
                </el-form-item>
                <el-form-item label="触发条件类型" prop="conditionType">
                    <el-select placeholder="请选条件类型" v-model="formData.conditionType" filterable>
                        <el-option v-for="(value, key) in ConditionType" :label="value" :key="key" :value="key" />
                    </el-select>
                </el-form-item>
                <el-form-item label="验证结果" prop="validationResult">
                    <el-radio-group v-model="formData.validationResult">
                        <el-radio v-for="(value, key) in ValidationResult" :key="key" :value="key">{{
                            value
                        }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item style="width: 100%; margin-left: 0" prop="errorMsg">
                    <template #label>
                        <div style="display: flex; align-items: center">
                            <span style="margin-right: 5px">提示信息</span>
                            <el-tooltip content="当不满足规则时，页面给出的提示信息。" placement="top">
                                <el-icon size="16"><InfoFilled /></el-icon>
                            </el-tooltip>
                        </div>
                    </template>
                    <el-input
                        v-model="formData.errorMsg"
                        @input="value => (formData.errorMsg = value.trim())"
                        placeholder="请输入提示信息"
                        maxlength="50"
                    />
                </el-form-item>
                <el-form-item label="描述" style="width: 100%; margin-left: 0">
                    <el-input
                        v-model="formData.description"
                        type="textarea"
                        maxlength="200"
                        show-word-limit
                        placeholder="请输入描述"
                    />
                </el-form-item>
                <TriggerCondition
                    ref="triggerConditionRef"
                    :row="row"
                    :conditionType="formData.conditionType"
                    :modelDetail="detailData"
                ></TriggerCondition>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <template v-if="!isLook()">
                        <el-button
                            type="primary"
                            @click="
                                () => {
                                    formData.enableStatus = true;
                                    submitForm();
                                }
                            "
                            :loading="loading"
                            >确定并启用</el-button
                        >
                        <el-button type="primary" @click="submitForm" :loading="loading">确定</el-button>
                        <el-button @click="props.close">取消</el-button>
                    </template>
                    <el-button v-else @click="props.close">关闭</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { modelService } from '@great/services';
import { ref } from 'vue';
import type { PopupBoxProps } from '@great/utils';
import { ConditionType, ValidationResult } from '@/utils/constant';
import { useRequest } from 'vue-request';
import type { FormInstance, FormRules } from 'element-plus';
import { InfoFilled } from '@element-plus/icons-vue';
import TriggerCondition from '@/components/TriggerCondition.vue';

interface IProps extends PopupBoxProps {
    row?: Record<string, any>;
    detailData: Record<string, any>;
    callBack?: () => Promise<void>;
}

const props = defineProps<IProps>();
interface Dialog {
    title: string;
    width: number;
    detail?: Record<string, any>;
}
const dialog = reactive<Dialog>({
    title: '新建规则',
    width: 900,
    detail: undefined
});
const elementRef = useTemplateRef('triggerConditionRef');
const formData = reactive({
    id: undefined,
    displayName: '',
    objectName: props.detailData.objectName,
    conditionType: '',
    validationResult: 'ERROR',
    errorMsg: '',
    description: '',
    enableStatus: false, // 禁用状态，默认不启用
    basicCondition: '' // 触发条件
});
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<FormRules<any>>({
    displayName: [{ required: true, message: '请输入规则名称', trigger: ['blur', 'change'] }],
    conditionType: [{ required: true, message: '请选条件类型', trigger: ['blur', 'change'] }],
    validationResult: [{ required: true, message: '请选条件类型', trigger: ['blur', 'change'] }],
    errorMsg: [{ required: true, message: '请输入提示消息', trigger: ['blur', 'change'] }]
});
// 是否为编辑
const isEdit = (par?: boolean): boolean => {
    if (par === undefined) {
        return dialog.title.includes('修改');
    } else {
        return dialog.title.includes('修改') && par;
    }
};
const isLook = () => {
    return dialog.title.includes('查看');
};
// 提交接口请求
const { run, loading } = useRequest(
    () => {
        return modelService.rules[isEdit() ? 'update' : 'create'](formData);
    },
    {
        manual: true,
        onSuccess() {
            ElNotification({
                title: isEdit() ? '修改成功！' : '新建成功！',
                type: 'success'
            });
            closeDialog();
        }
    }
);
// 表单提交
const submitForm = () => {
    ruleFormRef.value?.validate(valid => {
        if (!valid) return;
        let basicCondition = elementRef.value?.getCondition();
        if (basicCondition && basicCondition.length) {
            formData.basicCondition = JSON.stringify(basicCondition);
            run();
        } else {
            ElNotification({
                title: '请添加触发条件',
                type: 'warning'
            });
        }
    });
};

//关闭弹框
const closeDialog = () => {
    props.close();
    props.callBack?.();
};
// 打开弹框
const openDialog = () => {
    if (props.row) {
        dialog.title = props.callBack ? '修改规则' : '查看规则';
        dialog.detail = JSON.parse(JSON.stringify(props.row));
        formData.id = props.row.id;
        Object.keys(formData).forEach(key => {
            formData[key] = (props.row as any)[key];
        });
    }
};

const init = () => {
    openDialog();
};
init();
</script>
<style scoped lang="scss">
.rules-form-modal-wrapper {
    .el-form {
        display: flex;
        flex-wrap: wrap;
        .el-form-item {
            width: calc((100% - 10px) / 2);
        }
        .el-form-item:nth-child(even) {
            margin-left: 10px;
        }
    }
}
</style>
